首先是 658. Find K Closest Elements (medium)
https://leetcode.com/problems/find-k-closest-elements/
給定一個上升排序的numList與正整數k還有正整數x
要求找到最靠近x的k個正整數
想法都在註解
class Solution:
    #前k個靠近的
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        if x<arr[0]:#第0個比x還小就必定是前k個
            return arr[:k]
        elif x>arr[-1]:#最後一個比x還大就必定是最後k個
            return arr[-k:]
        if k == len(arr):#長度跟k一樣直接輸出
            return arr
        
        #找到最小開始的值
        L,R = 0,len(arr)-k#最右邊值少了k個
        
        while L < R:
            mid = (L+R)//2
            if x <= arr[mid]:#如果最小開始的值跟x一樣甚至比x大,那絕對不可能
                R = mid
            elif x >= arr[mid + k]:#2.如果x比最大值還大不可能(最右邊的值為arr[mid+k-1])
                L = mid + 1
            if x - arr[mid] > arr[mid+k] - x:#3.若x扣掉最小值比最右邊的值扣掉x還大也不合理(因為題目要求最小值要比最大值更加靠近)
                L = mid + 1
            else:
                R = mid
        return arr[L:L+k]
            
再來是 1046. Last Stone Weight (easy)
https://leetcode.com/problems/last-stone-weight/
給一個numList,裡面每個數字代表石頭大小,要把兩個最大的石頭相減,如果變成0就直接消失,如果還有數字就丟回list裡面繼續減,減到剩下一個或沒有為止
想法:
1.排序
2.丟出兩個最大的相減
3.放到一個templist當中,再從numList丟出最大兩個
4.tempList排序,選出最大兩個扣掉
5.扣到tempList沒東西為止
class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        sL = len(stones)
        if sL == 1:
            return stones[0]
        stones.sort(reverse = True)
        temp = [stones.pop(0),stones.pop(0)]
        while len(temp) > 1:
            # print(temp)
            if stones:
                temp.append(stones.pop(0))
            if stones:
                temp.append(stones.pop(0))
            temp.sort(reverse = True)
            if temp[0] == temp[1]:
                temp.pop(0)
                temp.pop(0)
            else:
                temp.append(temp.pop(0) - temp.pop(0))
                
        if temp:
            return temp[0]
        else:
            return 0
再來是 70. Climbing Stairs(easy)
https://leetcode.com/problems/climbing-stairs/
每次只能走1或2階樓梯,問跑到n皆有幾種走法
dp基本題
第n階樓梯的走法就是第n-1階+第n-2階的總合
class Solution:
    def climbStairs(self, n: int) -> int:
        if n<3:
            return n
        a,b = 1,2
        for i in range(n-2):
            a,b = b,a+b
        return b
以上為今天的練習感謝大家